import { onMounted, onUnmounted } from 'vue'
import type { AnyFunction } from '@/declare/common'

interface EventAble {
  addEventListener: (event: string, cb: AnyFunction) => any
  removeEventListener: (event: string, cb: AnyFunction) => any
}

interface EventAble2 {
  on: (event: string, cb: AnyFunction) => any
  off: (event: string, cb: AnyFunction) => any
}

const isEventAble = (obj: any): obj is EventAble => {
  return obj.addEventListener && obj.removeEventListener
}

export const useAddEventListener = (
  obj: EventAble | EventAble2,
  eventName: string,
  fn: AnyFunction
) => {
  onMounted(() => {
    if (isEventAble(obj)) {
      obj.addEventListener(eventName, fn)
    } else {
      obj.on(eventName, fn)
    }
  })
  onUnmounted(() => {
    if (isEventAble(obj)) {
      obj.removeEventListener(eventName, fn)
    } else {
      obj.off(eventName, fn)
    }
  })
}
